package com.kelly.kellymusicplayer.Utils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.kelly.kellymusicplayer.entity.MusicInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * 获取android手机本地音乐的工具
 * Created by kelly on 2015/12/13.
 */
public class MusicHelper {
    private static final Uri CONTENT_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    private static String SORT_ORDER = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;

    public static List<MusicInfo> getMusicInfo(ContentResolver contentResolver) {
        List<MusicInfo> musicList = new ArrayList<>();
        Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, SORT_ORDER);
        if (cursor == null) {
//            Log.v("MusicHelper", "Line(27  )   Music Loader cursor == null.");
        } else {
            if (!cursor.moveToFirst()) {
//                Log.v("MusicHelper", "Line(39  )   Music Loader cursor.moveToFirst() returns false.");
            } else {
                int displayNameCol = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
                int albumCol = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                int idCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
                int durationCol = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                int sizeCol = cursor.getColumnIndex(MediaStore.Audio.Media.SIZE);
                int artistCol = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                int urlCol = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                do {
                    String title = cursor.getString(displayNameCol);
                    String album = cursor.getString(albumCol);
                    long id = cursor.getLong(idCol);
                    int duration = cursor.getInt(durationCol);
                    long size = cursor.getLong(sizeCol);
                    String artist = cursor.getString(artistCol);
                    String url = cursor.getString(urlCol);

                    MusicInfo musicInfo = new MusicInfo(id, title);
                    musicInfo.setAlbum(album);
                    musicInfo.setDuration(duration);
                    musicInfo.setSize(size);
                    musicInfo.setArtist(artist);
                    musicInfo.setUrl(url);
                    musicList.add(musicInfo);

                } while (cursor.moveToNext());
            }
        }
        return musicList;
    }

}
